/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.manchini.stereocv.telas;

import br.com.manchini.stereocv.bd.ControleBD;
import br.com.manchini.stereocv.classes.parametrosdisparidade.ParamentrosDisparidade;
import br.com.manchini.stereocv.utils.CamResolucao;
import br.com.manchini.stereocv.utils.ImgUtils;
import br.com.manchini.stereocv.utils.MatcherUtils;
import br.com.manchini.stereocv.utils.RobustMatcher;
import com.googlecode.javacv.Blobs;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_calib3d;
import static com.googlecode.javacv.cpp.opencv_calib3d.cvFindStereoCorrespondenceBM;
import com.googlecode.javacv.cpp.opencv_core;
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_highgui.cvLoadImage;
import static com.googlecode.javacv.cpp.opencv_highgui.cvSaveImage;
import static com.googlecode.javacv.cpp.opencv_imgproc.CV_BGR2GRAY;
import static com.googlecode.javacv.cpp.opencv_imgproc.CV_INTER_LINEAR;
import static com.googlecode.javacv.cpp.opencv_imgproc.cvCvtColor;
import static com.googlecode.javacv.cpp.opencv_imgproc.cvRemap;
import com.googlecode.javacv.cpp.opencv_nonfree;
import static com.googlecode.javacv.cpp.opencv_photo.fastNlMeansDenoising;
import de.congrace.exp4j.Calculable;
import de.congrace.exp4j.ExpressionBuilder;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author manchini
 */
public class MedicaoDistancia extends javax.swing.JDialog {

    CvMat Q = new CvMat(cvLoad("Q.xml", null, null, null));
    CvMat M1 = new CvMat(cvLoad("M1.xml", null, null, null));
    CvMat M2 = new CvMat(cvLoad("M2.xml", null, null, null));
    CvMat D1 = new CvMat(cvLoad("D1.xml", null, null, null));
    CvMat D2 = new CvMat(cvLoad("D2.xml", null, null, null));
    CvMat R1 = new CvMat(cvLoad("R1.xml", null, null, null));
    CvMat R2 = new CvMat(cvLoad("R2.xml", null, null, null));
    CvMat mx1 = new CvMat(cvLoad("mx1.xml", null, null, null));
    CvMat my1 = new CvMat(cvLoad("my1.xml", null, null, null));
    CvMat mx2 = new CvMat(cvLoad("mx2.xml", null, null, null));
    CvMat my2 = new CvMat(cvLoad("my2.xml", null, null, null));
    private IplImage imgEsq;
    private CanvasFrame canvasFrame;
    private IplImage imgDir;
    private CvMat disparidade;
    private CvMat imgEsqP;
    private CvMat imgDirP;
    private CvMat blob;
    CvFont font = new CvFont(CV_FONT_HERSHEY_PLAIN, 1, 1);
    private CvMat mascaraEsq;
    private CvMat mascaraDir;
    private OpenCVFrameGrabber grabberEsq;
    private OpenCVFrameGrabber grabberDir;

    /**
     * Creates new form ImagemSequencia
     */
    public MedicaoDistancia(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        jComboBox_resolucao.setModel(new DefaultComboBoxModel(CamResolucao.values()));
        jComboBox_resolucao.setSelectedIndex(2);
    }

    private void carregaFoto() {
        try {
            Integer aux = (Integer) jSpinner_Cont.getValue();

            imgEsq = cvLoadImage("img/" + aux + "esq.jpg");

            if (jCheckBox_Retificar.isSelected()) {

                cvRemap(imgEsq, imgEsq, mx1, my1, CV_INTER_LINEAR, CvScalar.ZERO);

            }
            if (canvasFrame == null) {
                canvasFrame = new CanvasFrame("IMG");
                jPanel_camesq.add(canvasFrame.getCanvas());

                canvasFrame.setCanvasSize(imgEsq.width(), imgEsq.height());
                canvasFrame.getCanvas().addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        int x = e.getX();
                        int y = e.getY();
                        ArrayList<CvPoint> pontos = new ArrayList<>();
                        pontos.add(cvPoint(x, y));
                        carregaFoto();
                        mascaraEsq = cvCreateMat(imgDir.height(), imgDir.width(), CV_8UC1);
                        mascaraDir = cvCreateMat(imgDir.height(), imgDir.width(), CV_8UC1);

                        cvRectangle(mascaraEsq, new CvPoint(100, y - 20), new CvPoint(700, y + 20), CvScalar.WHITE, -1, 8, 0);

                        cvRectangle(mascaraDir, new CvPoint(100, y - 20), new CvPoint(700, y + 20), CvScalar.WHITE, -1, 8, 0);

                        calculaDistancia(pontos);
                    }
                });
            }
            canvasFrame.showImage(imgEsq);



            imgDir = cvLoadImage("img/" + aux + "dir.jpg");
            if (jCheckBox_Retificar.isSelected()) {
                cvRemap(imgDir, imgDir, mx2, my2, CV_INTER_LINEAR, CvScalar.ZERO);
            }

            // Se primeira vez, cria as variaveis de disparidade
            if (disparidade == null) {
                disparidade = cvCreateMat(imgDir.height(), imgDir.width(), CV_16SC1);
                blob = cvCreateMat(imgDir.height(), imgDir.width(), CV_16SC1);
                imgEsqP = opencv_core.CvMat.create(imgDir.height(), imgDir.width(), CV_8UC1);
                imgDirP = opencv_core.CvMat.create(imgDir.height(), imgDir.width(), CV_8UC1);
            }
            mascaraEsq = cvCreateMat(imgDir.height(), imgDir.width(), CV_8UC1);
            mascaraDir = cvCreateMat(imgDir.height(), imgDir.width(), CV_8UC1);


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Erro");
            ex.printStackTrace();
        }
    }

    private void processar() {

        ControleBD controleBD = new ControleBD();
        try {
            //CARREGA OS PARAMETROS DE DISPARIDADE DO BANCO, do ID informado na tela
            Integer id = new Integer(jTextField_id.getText());
            ParamentrosDisparidade paramentrosDisparidade = new ParamentrosDisparidade();
            paramentrosDisparidade.setId(id);
            ParamentrosDisparidade existe = null;
            if ((existe = (ParamentrosDisparidade) controleBD.existe(paramentrosDisparidade)) != null) {
                paramentrosDisparidade = existe;
            }


            //INSTANCIA o Objeto de StereoBM
            opencv_calib3d.StereoBM bm = new opencv_calib3d.StereoBM();
            bm.init(opencv_calib3d.StereoBM.BASIC_PRESET, paramentrosDisparidade.getNumberOfDisparities(), paramentrosDisparidade.getSadWindowSize());

            // Seta parametros de Disparidade
            bm.state().preFilterCap(paramentrosDisparidade.getPreFilterCap());
            bm.state().SADWindowSize(paramentrosDisparidade.getSadWindowSize());
            bm.state().preFilterSize(paramentrosDisparidade.getPreFilterSize());
            bm.state().minDisparity(paramentrosDisparidade.getMinDisparity());
            bm.state().numberOfDisparities(paramentrosDisparidade.getNumberOfDisparities());
            bm.state().textureThreshold(paramentrosDisparidade.getTextureThreshold());
            bm.state().uniquenessRatio(paramentrosDisparidade.getUniquenessRatio());
            bm.state().speckleWindowSize(paramentrosDisparidade.getSpeckleWindowSize());
            bm.state().speckleRange(paramentrosDisparidade.getSpeckleRange());
//            bm.state().disp12MaxDiff((Integer) jSpinner_disp12MaxDiff.getValue());



            //Converte para escala de cinza
            //para fazer a disparidade
            cvCvtColor(imgEsq, imgEsqP, CV_BGR2GRAY);
            cvCvtColor(imgDir, imgDirP, CV_BGR2GRAY);

            // remove ruidos
            fastNlMeansDenoising(imgEsqP, imgEsqP, 7, 21, 3);
            fastNlMeansDenoising(imgDirP, imgDirP, 7, 21, 3);

            //Calcula disparidade
            cvFindStereoCorrespondenceBM(imgEsqP, imgDirP, disparidade, bm.state());

            //Normaliza a saida da disparidade
            //remove os muito esculo
            cvNormalize(disparidade, disparidade, 0, 32, CV_MINMAX, null);

            cvCopy(disparidade, blob);
//           


            //Mostra a disparidade
            canvasFrame.showImage(blob.asIplImage());

            //Cria a variavel de busca de Blobs
            Blobs Regions = new Blobs();
            Regions.BlobAnalysis(
                    blob.asIplImage(), // image
                    250, 100, // ROI start col, row
                    550, 500, // ROI cols, rows
                    0, // border (0 = black; 1 = white)
                    100);                   // minarea
            Regions.PrintRegionData();

            //Cria os pontos dos blobs para calcular a distancia
            ArrayList<CvPoint> pontos = new ArrayList<>();
            for (int i = 1; i <= Blobs.MaxLabel; i++) {
                double[] Region = Blobs.RegionData[i];
//                int Parent = (int) Region[Blobs.BLOBPARENT];
//                int Color = (int) Region[Blobs.BLOBCOLOR];
                int MinX = (int) Region[Blobs.BLOBMINX];
                int MaxX = (int) Region[Blobs.BLOBMAXX];
                int MinY = (int) Region[Blobs.BLOBMINY];
                int MaxY = (int) Region[Blobs.BLOBMAXY];
//                
                CvPoint ptEsq1 = cvPoint(MinX, MinY);
                CvPoint ptEsq2 = cvPoint(MaxY, MaxY);
                CvPoint ptDir1 = cvPoint(250, MinY);
                CvPoint ptDir2 = cvPoint(550, MaxY);

                //desenha na mascara aonde foi encontrado os itens
                cvRectangle(mascaraEsq, ptEsq1, ptEsq2, CvScalar.WHITE, -1, 8, 0);
                //na iamgem da direita desenha em todo o X
                cvRectangle(mascaraDir, ptDir1, ptDir2, CvScalar.WHITE, -1, 8, 0);

                pontos.add(cvPoint((MinX + MaxX) / 2, (MinY + MaxY) / 2));
            }

            canvasFrame.showImage(mascaraEsq.asIplImage());

            calculaDistancia(pontos);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            controleBD.close();
        }

    }

    private void calculaDistancia(ArrayList<CvPoint> pontos) {
//
//            Calcula Pontos de Interresse
        RobustMatcher rMatcher = new RobustMatcher(
                0.50,
                3.0,
                0.65F,
                new opencv_nonfree.SURF(1));

        RobustMatcher.Result matches = rMatcher.matchImages(imgEsq, imgDir, mascaraEsq == null ? null : mascaraEsq.asIplImage(), mascaraDir == null ? null : mascaraDir.asIplImage());
        matches.getMatches();

        CvPoint2D32f[] points = MatcherUtils.toCvPoint2D32f(matches.getMatches(), matches.getKeyPoints1(), matches.getKeyPoints2());
        CvPoint2D32f point1 = points[0];
        CvPoint2D32f point2 = points[1];


        for (int i = 0; i < pontos.size(); i++) {
            System.out.println(pontos.get(i).x() + " x "
                    + pontos.get(i).y());
            Point ponto = new Point(pontos.get(i).x(), pontos.get(i).y());

            int indexPontoMaisProximo = MatcherUtils.getIndexPontoMaisProximo(ponto.x, ponto.y, point1);

            if (Math.abs(ponto.x - point1.position(indexPontoMaisProximo).x()) + Math.abs(ponto.y - point1.position(indexPontoMaisProximo).y()) > 40) {
                continue;
            }
            float modulo = (point1.position(indexPontoMaisProximo).x() - point2.position(indexPontoMaisProximo).x());

            //MODO BRIGO
            Double brigo = 0.0;
            Calculable calc = null;
            try {
                calc = new ExpressionBuilder(jTextFieldEntrada.getText())
                        .withVariable("x", modulo).build();
                brigo = calc.calculate();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            Float canonico = 0.0f;
            try {
                float d = (point1.position(indexPontoMaisProximo).x() - point2.position(indexPontoMaisProximo).x());

                float Z = ((Double) Q.get(2, 3)).floatValue();
                float W = d * ((Double) Q.get(3, 2)).floatValue() + ((Double) Q.get(3, 3)).floatValue();

                Z = Z / W;
                canonico = Z;

            } catch (Exception ex) {
                ex.printStackTrace();
            }

//                cvCircle(imgEsq, new CvPoint(ponto.x, ponto.y), 3, CvScalar.RED, 1, CV_AA, 0);
            cvCircle(imgEsq, new CvPoint(((Float) point1.position(indexPontoMaisProximo).x()).intValue(), ((Float) point1.position(indexPontoMaisProximo).y()).intValue()), 3, CvScalar.RED, 1, CV_AA, 0);

            cvPutText(imgEsq, "CANO = " + canonico.intValue(), new CvPoint(ponto.x + 5, ponto.y),
                    font, CvScalar.BLACK);
            cvPutText(imgEsq, " BRIGO = " + brigo.intValue(), new CvPoint(ponto.x + 5, ponto.y + 12),
                    font, CvScalar.BLACK);





        }
        canvasFrame.showImage(imgEsq);
//            canvasFrame.showImage(blob.asIplImage());
    }

    private void liveAction() {
        Integer camEsq = (Integer) jSpinner_esq.getValue();
        Integer camDir = (Integer) jSpinner_dir.getValue();




        CamResolucao camResolucao = (CamResolucao) jComboBox_resolucao.getSelectedItem();
        if (camEsq != -1) {
            try {
                grabberEsq = new OpenCVFrameGrabber(camEsq);
                grabberEsq.setImageWidth(camResolucao.getW());
                grabberEsq.setImageHeight(camResolucao.getH());
                grabberEsq.start();

                imgEsq = grabberEsq.grab();

                grabberEsq.setFrameRate(grabberEsq.getFrameRate());

            } catch (FrameGrabber.Exception ex) {
                Logger.getLogger(AjusteDisparidade.class.getName()).log(Level.SEVERE, null, ex);
            }


        }

        if (camDir != -1) {
            try {
                grabberDir = new OpenCVFrameGrabber(camDir);
                grabberDir.setImageWidth(camResolucao.getW());
                grabberDir.setImageHeight(camResolucao.getH());
                grabberDir.start();

                imgDir = grabberDir.grab();

                grabberDir.setFrameRate(grabberDir.getFrameRate());

            } catch (FrameGrabber.Exception ex) {
                Logger.getLogger(AjusteDisparidade.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        if (canvasFrame == null) {
            canvasFrame = new CanvasFrame("IMG");
            jPanel_camesq.add(canvasFrame.getCanvas());

            canvasFrame.setCanvasSize(imgEsq.width(), imgEsq.height());
        }
        

        new Thread(new Runnable() {
            @Override
            public void run() {

                while (true) {
                    try {
                        grabberEsq.flush();
                        grabberDir.flush();
                        
                        IplImage imgEsqOriginal = grabberEsq.grab();

                        if (jCheckBox_Rotaciona.isSelected()) {
                            ImgUtils.rotacionaImagem(imgEsqOriginal, imgEsq);
                        } else {
                            imgEsq = imgEsqOriginal;
                        }


                        IplImage imgDirOriginal = grabberDir.grab();

                        if (jCheckBox_Rotaciona.isSelected()) {
                            ImgUtils.rotacionaImagem(imgDirOriginal, imgDir);
                        } else {
                            imgDir = imgDirOriginal;
                        }
                        if (jCheckBox_Retificar.isSelected()) {
                            cvRemap(imgDir, imgDir, mx2, my2, CV_INTER_LINEAR, CvScalar.ZERO);
                            cvRemap(imgEsq, imgEsq, mx1, my1, CV_INTER_LINEAR, CvScalar.ZERO);
                        }
                        ArrayList<CvPoint> pontos = new ArrayList<>();
                        pontos.add(cvPoint(imgEsq.width()/ 2, imgEsq.height()/ 2));
                        
                        //Mascaras 
                        CvPoint ptEsq1 = cvPoint((imgEsq.width()/ 2)-50, (imgEsq.height()/ 2)-50);
                        CvPoint ptEsq2 = cvPoint((imgEsq.width()/ 2)+50, (imgEsq.height()/ 2)+50);
                        
                        CvPoint ptDir1 = cvPoint(150, (imgEsq.height()/ 2)-50);
                        CvPoint ptDir2 = cvPoint((imgEsq.width()/ 2)+50, (imgEsq.height()/ 2)+50);

                        //desenha na mascara aonde foi encontrado os itens
                        mascaraEsq = cvCreateMat(imgDir.height(), imgDir.width(), CV_8UC1);
                        mascaraDir = cvCreateMat(imgDir.height(), imgDir.width(), CV_8UC1);
                        cvRectangle(mascaraEsq, ptEsq1, ptEsq2, CvScalar.WHITE, -1, 8, 0);
                        cvRectangle(mascaraDir, ptDir1, ptDir2, CvScalar.WHITE, -1, 8, 0);
//                        new CanvasFrame("teste1").showImage(mascaraEsq.asIplImage());
//                        new CanvasFrame("teste2").showImage(mascaraDir.asIplImage());
                        try{
                            calculaDistancia(pontos);
                        }catch(Exception e){
                            e.printStackTrace();
                        }
                        cvLine(imgEsq, new CvPoint(imgEsq.width() / 2, 0), new CvPoint(imgEsq.width() / 2, imgEsq.height()), CvScalar.GREEN, 0, 0, 0);
                        cvLine(imgEsq, new CvPoint(0, imgEsq.height() / 2), new CvPoint(imgEsq.width(), imgEsq.height() / 2), CvScalar.RED, 0, 0, 0);
                        
                        canvasFrame.showImage(imgEsq);


                    } catch (FrameGrabber.Exception ex) {
                        Logger.getLogger(AjusteDisparidade.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

            }
        }).start();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel7 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jSpinner_esq = new javax.swing.JSpinner();
        jLabel2 = new javax.swing.JLabel();
        jSpinner_dir = new javax.swing.JSpinner();
        jCheckBox_Rotaciona = new javax.swing.JCheckBox();
        jComboBox_resolucao = new javax.swing.JComboBox();
        jCheckBox_Retificar = new javax.swing.JCheckBox();
        jLabel14 = new javax.swing.JLabel();
        jTextField_id = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jSpinner_Cont = new javax.swing.JSpinner();
        jButton4 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel_saida = new javax.swing.JLabel();
        jPanel8 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jLabel_saida3 = new javax.swing.JLabel();
        jTextFieldEntrada = new javax.swing.JTextField();
        jLabel_Formula = new javax.swing.JLabel();
        jPanel9 = new javax.swing.JPanel();
        jLabel_saida4 = new javax.swing.JLabel();
        jLabel_SaidaCanonico = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        jPanel_camesq = new javax.swing.JPanel();
        jPanel10 = new javax.swing.JPanel();
        jLabel_FPS = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });

        jPanel7.setLayout(new javax.swing.BoxLayout(jPanel7, javax.swing.BoxLayout.Y_AXIS));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Cameras"));

        jLabel1.setText("Esquerda");
        jPanel1.add(jLabel1);

        jSpinner_esq.setModel(new javax.swing.SpinnerNumberModel(1, -1, 5, 1));
        jPanel1.add(jSpinner_esq);

        jLabel2.setText("Direita");
        jPanel1.add(jLabel2);

        jSpinner_dir.setModel(new javax.swing.SpinnerNumberModel(2, -1, 5, 1));
        jPanel1.add(jSpinner_dir);

        jCheckBox_Rotaciona.setSelected(true);
        jCheckBox_Rotaciona.setText("Rotaciona Imagem");
        jCheckBox_Rotaciona.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox_RotacionaActionPerformed(evt);
            }
        });
        jPanel1.add(jCheckBox_Rotaciona);

        jPanel1.add(jComboBox_resolucao);

        jCheckBox_Retificar.setSelected(true);
        jCheckBox_Retificar.setText("Retificar");
        jCheckBox_Retificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox_RetificarActionPerformed(evt);
            }
        });
        jPanel1.add(jCheckBox_Retificar);

        jLabel14.setText("ID:");
        jPanel1.add(jLabel14);

        jTextField_id.setText("1");
        jTextField_id.setPreferredSize(new java.awt.Dimension(50, 27));
        jPanel1.add(jTextField_id);

        jPanel7.add(jPanel1);

        jSpinner_Cont.setModel(new javax.swing.SpinnerNumberModel(53, 0, 99999, 10));
        jPanel2.add(jSpinner_Cont);

        jButton4.setText("Carrega Fotos");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton4);

        jButton2.setText("Live Action");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);

        jPanel7.add(jPanel2);

        jPanel3.add(jLabel_saida);

        jPanel7.add(jPanel3);

        jPanel8.setLayout(new java.awt.BorderLayout());
        jPanel7.add(jPanel8);

        jTabbedPane1.addTab("Inicializar Imagens", jPanel7);

        jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.Y_AXIS));

        jLabel_saida3.setText("Em Função de X");
        jPanel5.add(jLabel_saida3);

        jTextFieldEntrada.setText("- 1.2563e-9*x^5 + 1.1586e-6*x^4 - 0.00039307*x^3 + 0.061819*x^2 - 4.8015*x + 199.77 ");
        jTextFieldEntrada.setPreferredSize(new java.awt.Dimension(450, 27));
        jTextFieldEntrada.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldEntradaActionPerformed(evt);
            }
        });
        jPanel5.add(jTextFieldEntrada);
        jPanel5.add(jLabel_Formula);

        jPanel4.add(jPanel5);

        jLabel_saida4.setText("Canonico:");
        jPanel9.add(jLabel_saida4);
        jPanel9.add(jLabel_SaidaCanonico);

        jPanel4.add(jPanel9);

        jPanel6.setLayout(new java.awt.BorderLayout());
        jPanel4.add(jPanel6);

        jTabbedPane1.addTab("Calculadora", jPanel4);

        getContentPane().add(jTabbedPane1, java.awt.BorderLayout.NORTH);

        jPanel_camesq.setPreferredSize(new java.awt.Dimension(600, 300));
        jPanel_camesq.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jPanel_camesqMouseClicked(evt);
            }
        });
        getContentPane().add(jPanel_camesq, java.awt.BorderLayout.CENTER);

        jPanel10.setPreferredSize(new java.awt.Dimension(1287, 20));
        jPanel10.add(jLabel_FPS);

        getContentPane().add(jPanel10, java.awt.BorderLayout.PAGE_END);

        setSize(new java.awt.Dimension(878, 669));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jCheckBox_RotacionaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox_RotacionaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCheckBox_RotacionaActionPerformed

    private void jPanel_camesqMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel_camesqMouseClicked
    }//GEN-LAST:event_jPanel_camesqMouseClicked

    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_formMouseClicked

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        carregaFoto();
//         processar();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jCheckBox_RetificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox_RetificarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCheckBox_RetificarActionPerformed

    private void jTextFieldEntradaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldEntradaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldEntradaActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        liveAction();
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MedicaoDistancia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MedicaoDistancia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MedicaoDistancia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MedicaoDistancia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                MedicaoDistancia dialog = new MedicaoDistancia(null, true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton4;
    private javax.swing.JCheckBox jCheckBox_Retificar;
    private javax.swing.JCheckBox jCheckBox_Rotaciona;
    private javax.swing.JComboBox jComboBox_resolucao;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel_FPS;
    private javax.swing.JLabel jLabel_Formula;
    private javax.swing.JLabel jLabel_SaidaCanonico;
    private javax.swing.JLabel jLabel_saida;
    private javax.swing.JLabel jLabel_saida3;
    private javax.swing.JLabel jLabel_saida4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JPanel jPanel_camesq;
    private javax.swing.JSpinner jSpinner_Cont;
    private javax.swing.JSpinner jSpinner_dir;
    private javax.swing.JSpinner jSpinner_esq;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextField jTextFieldEntrada;
    private javax.swing.JTextField jTextField_id;
    // End of variables declaration//GEN-END:variables
}